<?php
/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 14/11/21
 * Time: 上午11:35
 */

class UserService extends Service {

    public static function getUserByAccount($account, $app=false){
        $modUser     = new ModUser();

        $user = $modUser->findByAttributes(array('Account' => $account))->attributes;

        if(!empty($user)){
            if($app){
                $user['App'] = AppService::getAppByUser($user);
            }

            return $user;
        }else{
            return false;
        }
    }

    public static function getUserById($userID, $app=false){
        $modUser     = new ModUser();

        $user = $modUser->findByPk($userID)->attributes;

        if(!empty($user)){
            return $user;
        }else{
            return false;
        }
    }
    
    public static function getUserChannel($userId){
    	$modUserChannel = new ModUserChannel();
    	$params['user_id'] = $userId;
    	$result = $modUserChannel->select($params);
    	return $result;
    }
    
    public static function batchDelete($user_id){
    	$modUserChannel = new ModUserChannel();
    	$modUserChannel->deleteAll('user_id=:user_id', array(':user_id'=>$user_id));
    	return true;
    }
    

    public static function doChannel($channel,$id){
    	$channel_array = explode(',', $channel);
    	$modUserChannel = new ModUserChannel();
    	$server = array();
    	foreach ($channel_array as $key=>$val){
    		$data = array();
    		$data['user_id'] = $id;
    		$data['channel_id'] = $val;
    		array_push($server, $data);
    	}
    	$result = $modUserChannel->addUserChannel($server);
    	return array('state' => $result, 'msg' =>'分配成功');
    }
    
    


    /**
     * @return array 返回用户列表的表头
     */
    public static function indexHeader(){
        $header = array(
            'UserID' => array('text' => PubFunc::t('用户编号')),
            'Account' => array('text' => PubFunc::t('登录帐号')),
            'UserName' => array('text' => PubFunc::t('用户名')),
        	'RoleName' => array('text' => PubFunc::t('用户组')),
        	'Status' => array('text' => PubFunc::t('状态')),
        	'AddBy' => array('text' => PubFunc::t('创建人')),
        	'AddTime'=> array('text' => PubFunc::t('创建时间')),
            'Action' => array('text' => PubFunc::t('操作'))
        );

//         if(!AccAuth::isAdmin()){
//             unset($header['Action']);
//         }

        return $header;
    }

    /**
     * 返回用户列表的信息
     * @param $params   其中字段包括
     *      SystemID    (必须)系统ID
     *      SearchID    (可选)查找的信息
     *      UserType    (可选)用户类型
     *      Status      (可选)用户状态
     * @return mixed
     */
    public static function indexData($params){
    	$user = AccAuth::me();
    	if(!AccAuth::isAdmin()){
    		$params['AddBy'] = $user['UserID'];
    	}
    	
        $result = array();
        // 查找用户列表
        $modUser = new ModUser();
        $tmp = $modUser->page($params);
        $roleList = RoleaService::getRoleList(array(),2);
        $length = count($tmp['data']);
        $userList = self::userList();
        foreach($tmp['data'] as $k=>&$v){
        	$type = 1;
        	if($k == 0 && $length == 1){  //当前页只剩下一条数据时，删除之后需显示上一页的数据
        		$type = 2;
        	}
        	
        	$status_text = '';
        	if($v['Status'] == 1){
        		$status_text = '正常访问';
        	}
        	if($v['Status'] == 2){
        		$status_text = '禁止访问';
        	}
        	$v['Status'] = $status_text;
        	
        	$v['RoleName'] = $roleList[$v['RoleID']];
        	$v['AddBy'] = $userList[$v['AddBy']];
        	
        	if($v['UserID'] == 1 && AccAuth::isAdmin()){
        		$v['Action']  = ' <a href="'.PubFunc::buildBackUrl('/auth/?r=user/edit').'&id='.$v['UserID'].'">基础编辑&nbsp;&nbsp;</a>';
        	}else if($v['UserID'] == $user['UserID']){ //为当前自己的账号
        		$v['Action']  = ' <a href="'.PubFunc::buildBackUrl('/auth/?r=user/edit').'&id='.$v['UserID'].'">基础编辑&nbsp;&nbsp;</a>';
        	}else{
        		if($v['IsAdmin'] == 2){
        			$v['Action']  = ' <a href="'.PubFunc::buildBackUrl('/auth/?r=user/edit').'&id='.$v['UserID'].'">基础编辑&nbsp;&nbsp;</a>';
        			$v['Action'] .= "<a href='JavaScript:void(0);' name='set_channel' data-id='".$v['UserID']."' style='color:green;'>渠道分配&nbsp;&nbsp;</a>";	
        		}
        		if(AccAuth::isAdmin()){  //超级管理员才可以删除用户
        			$v['Action'] .= ' <a href="'.PubFunc::buildBackUrl('/auth/?r=user/delete',$type).'&id='.$v['UserID'].'" onclick="del()" confirm="是否要删除该条服信息?">删除</a>';
        		}
        	}
        }
        unset($v);
        return $tmp;
    }

    /**
     * 获得授权用户列表
     * @return array
     */
    public static function getGrantUser(){
        $modUser = new ModUser();

        $tmp = $modUser->findAllByAttributes(array(
            'AccAdmin' => 2
        ));
        $result = array();

        foreach($tmp as $v){
            $result[$v->UserID] = "[{$v->Account}] {$v->UserName}";
        }
        return $result;
    }

    /**
     * 增加一个用户
     * @param $user
     * @return bool|int
     */
    public static function add($user){
        self::beginTransaction();

        $modUser = new ModUser();

        $addBy   = AccAuth::me('UserID');
        $addTime = date('Y-m-d H:i:s');

        $modUser->Account   = $user['account'];
        $modUser->UserName  = $user['username'];
        $modUser->Status    = '1';
        $modUser->Password  = md5($user['password']);
        $modUser->AddBy     = $addBy;
        $modUser->AddTime   = $addTime;
        $modUser->IsAdmin   = $user['accadmin'];
        $modUser->IsViewAll   = $user['accall'];
        $modUser->Status   = $user['Status'];

        if($modUser->save()){
        	//非超级管理员用户保存成功保存用户的角色
        	if($user['accadmin'] == 2){
        		$modUserRoleMap = new ModUserRoleMap();
        		$modUserRoleMap->UserID = $modUser['UserID'];
        		$modUserRoleMap->RoleID = $user['RoleID'];
        		$modUserRoleMap->AddBy     = $addBy;
        		$modUserRoleMap->AddTime   = $addTime;
        		$modUserRoleMap->save();
        	}
        	
            self::commit();
            return $modUser->getDbConnection()->getLastInsertID();
        }else{
            self::commit();
            return false;
        }
    }

    /**
     * 编辑一个用户
     * @param $user
     */
    public static function edit($user){
        if(PubFunc::checkEmpty($user, array('id'))) return false;

        $modUser = new ModUser();


        $editBy   = AccAuth::me('UserID');
        $editTime = date('Y-m-d H:i:s');

        $attr['Account']    = $user['account'];
        $attr['UserName']   = $user['username'];
        $attr['Email']      = $user['email'];
        $attr['IsAdmin']    = $user['accadmin'];
        $attr['IsViewAll']    = $user['accall'];
        $attr['Status']   = $user['Status'];
        $attr['EditBy']     = $editBy;
        $attr['EditTime']   = $editTime;

        if(!empty($user['password'])){
            $attr['Password']   = md5($user['password']);
        }

        try{
            $modUser->updateByPk($user['id'], $attr);
            
            //删除旧的用户-角色关系
            $modUserRoleMap = new ModUserRoleMap();
            $modUserRoleMap->deleteAllByAttributes(array(
            		'UserID' => $user['id'],
            ));
            //非超级管理员则加入关系
            if($user['accadmin'] == 2){
            	$modUserRoleMap->UserID = $user['id'];
            	$modUserRoleMap->RoleID = $user['RoleID'];
            	$modUserRoleMap->AddBy     = $editBy;
            	$modUserRoleMap->AddTime   = $editTime;
            	$modUserRoleMap->save();
            }

            self::commit();
            return true;
        }catch (Exception $e){
            self::commit();
            return false;
        }
    }
    
    /**
     * 修改密码
     * @param $user
     */
    public static function doEditSelf($user){
    	if(PubFunc::checkEmpty($user, array('id'))) return false;
    	$modUser = new ModUser();
    	$editBy   = AccAuth::me('UserID');
    	$editTime = date('Y-m-d H:i:s');
    
    	$attr['Account']    = $user['account'];
    	$attr['UserName']   = $user['username'];
    	$attr['EditBy']     = $editBy;
    	$attr['EditTime']   = $editTime;
    
    	if(!empty($user['password'])){
    		$attr['Password']   = md5($user['password']);
    	}
    
    	try{
    		$modUser->updateByPk($user['id'], $attr);
    		self::commit();
    		return true;
    	}catch (Exception $e){
    		self::commit();
    		return false;
    	}
    }

    public static function editSelf($user){
        $id = AccAuth::me('UserID');

        $attr = array('Email' => $user['email']);
        if(!empty($user['password'])){
            $attr['Salt']       = self::getSalt();
            $attr['Password']   = self::encrypt($id, $user['password'], $attr['Salt']);
        }

        try{
            ModUser::model()->updateByPk($id, $attr);
            $me = AccAuth::me();
            $me['Email'] = $user['email'];
            Yii::app()->session['user'] = $me;
            return true;
        }catch (Exception $e){
            return false;
        }
    }

    public static function addUserType($userId, $array){
        if(empty($array)) return true;

        $modUserType = new ModUserType();

        $addBy   = AccAuth::me('UserID');
        $addTime = date('Y-m-d H:i:s');

        $r2 = true;

        foreach($array as $k=>$v){
            if(empty($v)) continue;

            $modUserType->setIsNewRecord(true);
            $modUserType->UserID    = $userId;
            $modUserType->AppID     = $k;
            $modUserType->UserType  = $v;
            $modUserType->AddBy     = $addBy;
            $modUserType->AddTime   = $addTime;

            if(!$modUserType->save()){
                $r2 = false;
                break;
            }
        }

        return $r2;
    }

    /**
     * 加密登录密码
     * @param $userID       用户ID
     * @param $pwd          密码
     * @param string $salt  盐值
     * @return string       加密后的密码
     */
    public static function encrypt($userID, $pwd, $salt){
        return md5($userID.$pwd.$salt);
    }

    /**
     * 获得加密的盐值
     * @return string   8位随机字母、符号组成的盐值
     */
    public static function getSalt(){
        return PubFunc::getRandomtext(8);
    }

    /**
     * @return array 用户类型列表
     */
    public static function userTypeOptions(){
        return array(
//            'SA' => PubFunc::t('系统管理员'),
//            'GA' => PubFunc::t('授权管理员'),
            'DV' => PubFunc::t('开发者'),
            'UR' => PubFunc::t('普通用户'),
        );
    }

    /**
     * @return array 用户类型列表
     */
    public static function statusOptions(){
        return array(
            '1' => PubFunc::t('正常访问'),
            '2' => PubFunc::t('禁止访问'),
        );
    }

    public static function delete($id){
        try{
            ModUser::model()->deleteAllByAttributes(array('UserID' => $id));
            ModUserRoleMap::model()->deleteAllByAttributes(array('UserID' => $id));
            return true;
        }catch (Exception $e){
            return false;
        }
    }

    public static function updateByArr($userId, $arr){
        return ModUser::model()->updateByPk($userId, $arr);
    }

    public static function getGameList(){
        $tmp = AccAuth::getMyGame();
        $result = array();

        foreach($tmp['Game'] as $gk=>$gi){
            $result[$gk] = array(
                'id'        => $gi['GameID'],
                'name'      => "{$gi['GameName']} [{$gi['GameNameEn']}]",
                'platform'  => array()
            );

            foreach($tmp['Platform'] as $pk=>$pi){
                if(isset($tmp['Details'][PubFunc::getGameKey($pk, $gi['GameID'])])){
                    $result[$gk]['platform'][$pk] = $pi['PlatformName'];
                }
            }
        }

        return array(
            'game'      => $result,
            'platform'  => $tmp['Platform']
        );
    }

    public static function grantMenu($user, $add, $delete){
        if(empty($user)) return false;

        $myMenu = AccAuth::getMyMenu(AccAuth::me('UserID'));

        if(!empty($myMenu)){
            $menuKey = array_keys($myMenu);

            $add = array_intersect($add, $menuKey);
            $delete = array_intersect($delete, $menuKey);
        }

        try{
            self::beginTransaction();
            $modUserMenuMap = new ModUserMenuMap();

            $modUserMenuMap->deleteAllByAttributes(array(
                'UserID' => $user,
                'MenuID' => $delete
            ));

            $kv         = array();
            $addBy      = AccAuth::me('UserID');
            $addTime    = date('Y-m-d H:i:s');
            foreach($add as $v){
                $kv[] = array(
                    'UserID'    => $user,
                    'MenuID'    => $v,
                    'AddBy'     => $addBy,
                    'AddTime'   => $addTime
                );
            }

            $modUserMenuMap->getDbConnection()->multiInsert($kv, $modUserMenuMap->getTable(), true);

            self::commit();
            return true;
        }catch (Exception $e){
            self::rollback();
            return false;
        }
    }
    
    /**
     * 去重
     * @param number $id  主键id
     * @param unknown $field 检查是否重复的字段名
     * @param unknown $val 检查是否重复的值
     * @return number
     */
    public static function repeat($id = 0, $field, $val){
    	$modUser = new ModUser();
    	$conut = $modUser->repeat($id, $field, $val);
    	return $conut;
    }
} 